package com.cn.shuangzi.util;

/**
 * Created by CN.
 */
import android.content.Context;
import android.text.TextUtils;

import com.cn.shuangzi.common.SZConst;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ChannelUtil {

    private static final String DEFAULT_CHANNEL = "own";
    private static final String CHANNEL_FILE_NAME = "channel.txt";
    private static String channel;

    /**
     * 从 assets/channel.txt 读取渠道信息
     */
    public static String getChannel(Context context) {
        InputStream is = null;
        try {
            /**从缓存中取渠道信息，如有则返回渠道信息*/
            if(SZValidatorUtil.isValidString(channel)){
                return channel;
            }

            /**没有渠道信息，进本地文件读取*/
            // 1. 打开 assets 中的文件流
            is = context.getAssets().open(CHANNEL_FILE_NAME);
            // 2. 读取文件内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            channel = reader.readLine().trim(); // 读取第一行并去除空格
            if (TextUtils.isEmpty(channel)) {
                return DEFAULT_CHANNEL;
            }
        } catch (IOException e) {
            SZUtil.logError( "从assets读取渠道失败: " + e.getMessage());
            return DEFAULT_CHANNEL;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return channel;
    }
}
